package com.sdp.flow.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.vo.Result;
import com.sdp.flow.db.entity.ActTemplateInfo;
import com.sdp.flow.db.service.IActTemplateInfoService;
import com.sdp.flow.dto.FlowInstanceParam;
import com.sdp.flow.dto.FlowInstanceResult;
import com.sdp.flow.dto.FlowTaskParam;

/**
 * <p>
 *  流程操作控制器(废弃不用)
 * </p>
 *
 * @author qcy
 * @since 2021-06-30
 */
@RestController
@RequestMapping("/flowRuntime")
public class FlowRuntimeController {

	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
    protected HistoryService historyService;
	
	@Autowired
    protected IActTemplateInfoService templateInfoService;
	
	@RequestMapping(value="/startFlow")
	public Result<?> startFlow(@RequestBody FlowInstanceParam<Map<String, Object>> param) {
		if (param != null && !StringUtils.isEmpty(param.getFlowId()) && !StringUtils.isEmpty(param.getBizId())) {
			//先查询流程模板信息，方便塞入流程实例中的冗余数据
			QueryWrapper<ActTemplateInfo> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(ActTemplateInfo::getKeyId, param.getFlowId());
			ActTemplateInfo model = templateInfoService.getOne(queryWrapper, false);
			if (model != null) {
				//流程启动额外参数
				Map<String, Object> variables = null;
				if (param.getData() != null) {
					variables = param.getData();
				} else {
					variables = new HashMap<>();
				}
//				//流程启动人员设置
//				String userId = ContextManager.getContextData(ConstantsEnum.token中账号的属性名.getCode());
//				if (!StringUtils.isEmpty(param.getStartUserId())) {
//					userId = param.getStartUserId();
//				}
//				Authentication.setAuthenticatedUserId(userId);
//				
//				// 获取流程构造器，设置流程实例冗余信息
//			    ProcessInstanceBuilder processInstanceBuilder = runtimeService.createProcessInstanceBuilder();
//			    processInstanceBuilder.name(model.getTemplateName())
//			    	.businessKey(param.getBizId())
//			    	.processDefinitionKey(param.getFlowId())
//			    	.variables(variables);
//			    
//			    ProcessInstance processInstance = processInstanceBuilder.start();
			    
				ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(param.getFlowId(), param.getBizId(), variables);
				
				
				//重置流程处理人
			    //Authentication.setAuthenticatedUserId(null);
				
			    //返回流程信息
			    FlowInstanceResult instanceResult = new FlowInstanceResult();
				instanceResult.setBizId(processInstance.getBusinessKey());
				instanceResult.setInstanceId(processInstance.getId());
				instanceResult.setDeploymentId(processInstance.getDeploymentId());
				instanceResult.setFlowName(processInstance.getProcessDefinitionName());
				instanceResult.setFlowVersion(processInstance.getProcessDefinitionVersion());
				instanceResult.setStartTime(processInstance.getStartTime());
				instanceResult.setStartUserId(processInstance.getStartUserId());
				
				return Result.ok(instanceResult);
			} else {
				return Result.error("flowId对应的流程模板不存在!");
			}

		} else {
			return Result.error("flowId和bizId不能为空!");
		}
			
	}
	
	@RequestMapping(value="/commitTask")
	public Result<?> commitTask(@RequestBody FlowTaskParam<Map<String, Object>> param) {
		if (param != null && !StringUtils.isEmpty(param.getTaskId())) {
			Task task = taskService.createTaskQuery().taskId(param.getTaskId()).singleResult();
			if (task != null) {
				Map<String, Object> variables = null;
				if (param.getData() != null) {
					variables = param.getData();
				} else {
					variables = new HashMap<>();
				}
				taskService.complete(param.getTaskId(), variables);
				return Result.ok();
			} else {
				return Result.error("流程不存在!");
			}
			
		} else {
			return Result.error("taskId不能为空!");
		}
	}
	
	@RequestMapping(value="/getTaskListByUser")
	public Result<?> getTaskListByUser(@RequestParam String userId) {
		if (!StringUtils.isEmpty(userId)) {
			List<Task> tasks = taskService.createTaskQuery().taskAssignee(userId).orderByTaskCreateTime().desc().list();
			return Result.ok(tasks);
		} else {
			return Result.error("userId不能为空!");
		}
	}
	
	
}
